package com.swotplus.admin.web.weixin;


import cn.hutool.core.bean.BeanUtil;
import com.swotplus.common.utils.StringUtils;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.WxMpMassVideo;
import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swotplus.common.core.AjaxResult;
import com.swotplus.framework.web.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.swotplus.system.weixin.service.WxcmsAccountFansService;
import java.util.*;
import com.swotplus.system.weixin.entity.WxcmsAccountFans;
import com.swotplus.system.weixin.service.WxcmsAccountFansService;
import org.springframework.stereotype.Controller;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hugang
 * @since 2020-06-04
 */
@Controller
@RequestMapping("/wxcmsAccountFans")
public class WxcmsAccountFansController extends BaseController {

    private String prefix = "/weixin/fans";

    private static  final   String LANG = "zh_CN"; //语言


    @Autowired
    private WxcmsAccountFansService wxcmsAccountFansService;

    @Autowired
    private WxMpService wxMpService;





    /**
     *  一次拉取调用最多拉取10000个关注者的OpenID，可以通过多次拉取的方式来满足需求。
     */
    @RequestMapping("syncAccountFansList")
    @ResponseBody
    public AjaxResult wxUserList(String nextOpenId){
        try {
            //拉取粉丝信息
            WxMpUserList wxUserList = wxMpService.getUserService().userList(nextOpenId);
            wxUserList.getCount();
            wxUserList.getNextOpenid();
            wxUserList.getTotal();
            List<String> openidlist=wxUserList.getOpenids();
            List<WxcmsAccountFans> fans=new ArrayList<>();
            for (String openid:openidlist
                    ) {
                //获取微信用户信息
                WxMpUser user = wxMpService.getUserService().userInfo(openid,LANG);
                WxcmsAccountFans wxcmsAccountFans=new WxcmsAccountFans();
                BeanUtil.copyProperties(user, wxcmsAccountFans);
                QueryWrapper<WxcmsAccountFans> qw=new QueryWrapper<>();
                qw.eq("openid",user.getOpenId());
                WxcmsAccountFans newWxcmsAccountFans=wxcmsAccountFansService.getOne(qw);
                if(newWxcmsAccountFans!=null){
                    wxcmsAccountFans.setId(newWxcmsAccountFans.getId());
                }
                fans.add(wxcmsAccountFans);
            }
            wxcmsAccountFansService.saveOrUpdateBatch(fans, wxUserList.getCount());
            //如果有下个openid 进行递归
            if(StringUtils.isNotBlank( wxUserList.getNextOpenid())){
                wxUserList( wxUserList.getNextOpenid());
            }
            return  AjaxResult.success();
        }catch (WxErrorException E){
            E.printStackTrace();
            return  AjaxResult.error();
        }catch (Exception e){
            e.printStackTrace();
            return  AjaxResult.error();
        }
    }


    /**
     *  根据OpenID获取用户最新信息。
     */
    @RequestMapping("syncAccountFans")
    @ResponseBody
    public AjaxResult wxUserUpdate(String openid){
        try {
                //获取微信用户信息
                WxMpUser user = wxMpService.getUserService().userInfo(openid,LANG);
                WxcmsAccountFans wxcmsAccountFans=new WxcmsAccountFans();
                BeanUtil.copyProperties(user, wxcmsAccountFans);
                QueryWrapper<WxcmsAccountFans> qw=new QueryWrapper<>();
                qw.eq("openid",user.getOpenId());
                WxcmsAccountFans newWxcmsAccountFans=wxcmsAccountFansService.getOne(qw);
                if(newWxcmsAccountFans!=null){
                    wxcmsAccountFans.setId(newWxcmsAccountFans.getId());
                }
                wxcmsAccountFansService.saveOrUpdate(wxcmsAccountFans);
            return  AjaxResult.success();
        }catch (WxErrorException E){
            E.printStackTrace();
            return  AjaxResult.error();
        }catch (Exception e){
            e.printStackTrace();
            return  AjaxResult.error();
        }
    }



    @RequestMapping("/list")
    @RequiresPermissions("wxcmsAccountFans:view")
    public String toHtml(){
         return prefix + "/fans";
    }



    @RequestMapping("/listData")
    @RequiresPermissions("wxcmsAccountFans:list")
    @ResponseBody
    public AjaxResult listData(WxcmsAccountFans wxcmsAccountFans, Integer page, Integer limit){
        try
        {
            QueryWrapper<WxcmsAccountFans> wrapper = new QueryWrapper<>();
            Page<WxcmsAccountFans> pageList = wxcmsAccountFansService.page(new Page<>(page,limit), wrapper);
            return AjaxResult.success("成功", (int) pageList.getTotal(),pageList.getRecords());
        } catch (Exception e)
        {
            return AjaxResult.warn(e.getMessage());
        }

    }

    /**
     * 新增保存
     */
    @RequestMapping("/add")
    @RequiresPermissions("wxcmsAccountFans:add")
    @ResponseBody
    public AjaxResult add(WxcmsAccountFans wxcmsAccountFans){

        try
        {
            return toAjax(wxcmsAccountFansService.save(wxcmsAccountFans));
        } catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
    * 删除
    */
    @RequestMapping("/remove")
    @RequiresPermissions("wxcmsAccountFans:del")
    @ResponseBody
    public  AjaxResult delBatch(String ids){

        try
        {
            List<String> ListStr = Arrays.asList(ids.split(",")).stream().map(s -> s.trim()).collect(Collectors.toList());
            return toAjax(wxcmsAccountFansService.removeByIds(ListStr));
        } catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
    * 编辑
    */
    @RequestMapping("/edit")
    @RequiresPermissions("wxcmsAccountFans:edit")
    @ResponseBody
    public AjaxResult edit(WxcmsAccountFans wxcmsAccountFans){
       try
        {
            return toAjax(wxcmsAccountFansService.updateById(wxcmsAccountFans));
        } catch (Exception e)
        {
            return error(e.getMessage());
        }


    }

}

